/**
 * 
 */
package com.google.gwt.sample.stockwatcher.server;

/**
 * @author Prashanth
 *
 */
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.google.gwt.sample.stockwatcher.client.ItemSuggestService;
import com.google.gwt.sample.stockwatcher.client.ItemSuggestion;
import com.google.gwt.user.client.ui.SuggestOracle;
import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
public class ItemSuggestServiceImpl extends RemoteServiceServlet 
implements ItemSuggestService { 
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public SuggestOracle.Response getSuggestions(SuggestOracle.Request 
req) { 
        SuggestOracle.Response resp = new SuggestOracle.Response(); 

     
        //System.out.println("server side request "+req.getQuery());
        List<Suggestion> suggestions = new ArrayList<Suggestion>(req.getLimit());
		try {
			FileReader stockFileReader = new FileReader("war/input/NASDAQ.txt");
			BufferedReader br = new BufferedReader(stockFileReader);
			br.readLine();
			ArrayList<String> masterSymbolList = new ArrayList<String>();
			while(br.ready()){
				masterSymbolList.add(br.readLine());
				//String totalString = br.readLine();
				//String symbol = totalString.substring(0, 5).trim();
				//suggestions.add(new ItemSuggestion(totalString,symbol));
				//suggestions.add(br.readLine());
			}	
			
			//add suggestion based on the request string
			String requestString = req.getQuery().trim();
			for(int i=0; i<masterSymbolList.size(); i++){
				String symbolAndText = masterSymbolList.get(i);
				String symbol = masterSymbolList.get(i).substring(0, 5);
				if(symbol.startsWith(requestString)){
					suggestions.add(new ItemSuggestion(symbolAndText,symbol));
				}
			}
			
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       
        // Now set the suggestions in the response 
        resp.setSuggestions(suggestions); 
        System.out.println("actual size***"+suggestions.size());
        // Send the response back to the client 
        return resp; 
    } 
} 